<template>
	<view>
		<view class="content">
			<!-- 申报 -->
			<block v-if="action == 'add' || action == 'editApply'">
				<u-form :model="formData" ref="uForm" label-align="center" :label-style="labelStyle" :error-type="errorType" label-width=220>
					<u-form-item prop="applicant_name" label="申请人姓名" required>
						<u-input type="text" confirmType="next" placeholder=" " v-model="formData.applicant_name" trim
							:custom-style="styles" :placeholderStyle="placeholderStyle" />
					</u-form-item>
					<u-form-item prop="applicant_phone" label="电话" required>
						<u-input type="text" maxlength="11" confirmType="next" placeholder=" " v-model="formData.applicant_phone" trim
							:custom-style="styles" :placeholderStyle="placeholderStyle" />
					</u-form-item>
					<u-form-item prop="applicant_sex" label="性别">
						<u-radio-group v-model="formData.applicant_sex" @change="changeApplicant_sex">
							<u-radio v-for="(item, index) in gander" :key="index" :name="item.text">
								{{item.text}}
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item prop="applicant_age" label="年龄">
						<u-input type="select" placeholder=" " v-model="formData.applicant_age" trim
							:custom-style="styles" :placeholderStyle="placeholderStyle" @click="showAge = true" />
					</u-form-item>
					<u-form-item prop="applicant_id_number" label="身份证号">
						<u-input type="text" confirmType="next" placeholder=" " v-model="formData.applicant_id_number" trim
							:custom-style="styles" :placeholderStyle="placeholderStyle" @blur="blurApplicant_id_number" />
					</u-form-item>
					<u-form-item prop="content" label="事由" class="form-item-top" label-position="top" label-align="left" required>
						<view class="tag-bar">
							<u-tag class="tag" v-for="(item, index) in categoryList" :key="index"
								 :text="item.name" mode="plain" shape="circle"
								 @click="clickTag(index)"
							/>
						</view>
						<u-input type="textarea" trim v-model="formData.content"
							:custom-style="styles" :placeholderStyle="placeholderStyle" />
					</u-form-item>
				</u-form>
				<u-select v-model="showAge" :list="ageOptions" value-name="text"
					label-name="text" @confirm="confirmAge"/>
			</block>
			<block v-else>
				<u-form label-width=220 label-align="center" :label-style="labelStyle">
					<u-form-item label="处理状态"> {{ statusText }} </u-form-item>
					<u-form-item v-if="formData.audit_reject_reason" label="拒绝原因">
							<text style="color:red;">{{ formData.audit_reject_reason }}</text> 
					</u-form-item>
		
					<u-form-item label="姓名"> {{ formData.applicant_name }} </u-form-item>
					<u-form-item label="电话"> {{ formData.applicant_phone }} </u-form-item>
					<u-form-item label="性别"> {{ formData.applicant_sex }} </u-form-item>
					<u-form-item label="年龄"> {{ formData.applicant_age || '' }} </u-form-item>
					<u-form-item label="身份证号"> {{ formData.applicant_id_number }} </u-form-item>
					<u-form-item label="事由"> {{ formData.content }} </u-form-item>
					
					<u-form-item label="申请日期"> {{ formData._add_time_str }} </u-form-item>
				</u-form>
			</block>
			
			<u-button v-if="action == 'add'" class="bottom" type="primary" :disabled="disabled" :loading="loading"
				@click="submit">提交申请</u-button>
			<view class="bottom-bar" v-if="action == 'editApply'">
				<u-button type="primary" :disabled="disabled" :loading="loading"
					@click="submit">重新提交申请</u-button>
				<u-button type="error" :disabled="disabled" :loading="loading"
					@click="withdraw">撤回</u-button>
			</view>
			<view class="bottom-bar" v-if="action == 'audit'">
				<u-button type="primary" :disabled="disabled" :loading="loading"
					@click="audit(3)">受理</u-button>
				<u-button type="error" :disabled="disabled" :loading="loading"
					@click="audit(-1)">不予受理</u-button>
			</view>
			<view class="bottom-bar" v-if="action == 'working'">
				<u-button type="primary" :disabled="disabled" :loading="loading"
					@click="over">完成</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import config from "@/app.config.js";
	
	let gander = [{
			"text": "未知"
		},
		{
			"text": "男"
		},
		{
			"text": "女"
		}
	]
	let ageOptions = [{
			"text": "18岁以下"
		},
		{
			"text": "19~26岁"
		},
		{
			"text": "27~45岁"
		},
		{
			"text": "46岁以上"
		}
	]
	export default {
		data() {
			// 姓名、电话、性别、年龄段、事由->纠纷类型（三大类+其他）
			let formData = {
				applicant_name: '',
				applicant_phone: '',
				applicant_sex: '',
				applicant_age: '',
				applicant_id_number: '',
				category_ids: [],
				category_names: [],
				content: '',
				article_status: null,
			}
			return {
				id: '',

				action: 'add',
				isAdmin: false,
				isEmployee: false,
				
				gander,
				
				showAge: false,
				ageOptions,
				
				showCategory: false,
				categoryList: vk.getVuex('$app.appInfo.categoryList'),

				formData,
				
				rules: {
					"applicant_name": [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur',
					}],
					"applicant_phone": [{
							required: true,
							message: '请输入电话',
							trigger: 'blur',
						}, {
							validator: (rule, value, callback) => {
								return vk.pubfn.checkStr(value, 'mobile');
							},
							message: '请输入11位手机号码',
							trigger: ['change', 'blur'],
						}
					],
					"content": [{
						required: true,
						message: '请输入事由',
						trigger: 'change',
					}],
				},
				placeholderStyle: this.$css.placeholderStyle,
				styles: this.$css.styles,
				errorType: this.$css.errorType,
				labelStyle: this.$css.labelStyle,
			}
		},
		computed: {
			categoryText() {
				if (this.formData.category_names && this.formData.category_names.length == 2) return this.formData
					.category_names[0] + '/' + this.formData
					.category_names[1];
				else return ""
			},
			statusText() {
				if (this.formData.article_status == -1) return '不予受理'
				if (this.formData.article_status == 2) return '待受理'
				if (this.formData.article_status == 3) return '已受理'
				if (this.formData.article_status == 11) return '已完结'
			},
		},
		onReady() {
			if (this.$refs.uForm) this.$refs.uForm.setRules(this.rules);
		},
		onLoad(options) {
			this.initPage(options);
		},
		methods: {
			initPage(options = {}) {				
				if(vk.pubfn.isNotNull(vk.getVuex("$user.userInfo")) && options.id){
					this.id = options.id;
					this.getData();
				}
				
				if (!this.formData.applicant_name) {
					this.formData.applicant_name = vk.getVuex("$user.userInfo.nickname")
					this.formData.applicant_id_number = vk.getVuex("$user.userInfo.applicant_id_number")
					this.formData.applicant_sex = vk.getVuex("$user.userInfo.sex")
					this.formData.applicant_age = vk.getVuex("$user.userInfo.age")
					this.formData.applicant_phone = vk.getVuex("$user.userInfo.mobile")
				}
				if (!this.formData.applicant_sex) this.formData.applicant_sex = vk.getVuex("$user.userInfo.sex") || gander[0].text;
			},
			changeApplicant_sex(e) {
				this.formData.applicant_sex = e
			},
			blurApplicant_id_number(){
				// if (this.formData.applicant_id_number && this.formData.applicant_id_number.length == 18) 
				// 	this.formData.applicant_age = this.$tools.calculateAgeByIDNumber(this.formData.applicant_id_number);
			},
			clickTag(index){
				console.log('点击tag', index, this.categoryList)
				this.formData.content = this.categoryList[index].name;
			},
			// 选中年龄段
			confirmAge(e) {
				this.formData.applicant_age = e[0].value
			},
			// // 选中纠纷类型
			// confirmCategory(e) {
			// 	this.formData.category_names = [e[0].label, e[1].label]
			// 	this.formData.category_ids = [e[0].value, e[1].value]
				
			// 	if (this.formData.category_names && this.formData.category_names.length == 2){
			// 		this.formData.content = this.formData.category_names[0] + '/' + this.formData.category_names[1];
			// 	}
			// },
			// 读取详情
			getData() {
				const role = vk.getVuex("$user.userInfo.role[0]");
				
				vk.callFunction({
						url: this.$api.NewsInfo,
						loading: true,
						data: {
							_id: this.id
						}
					})
					.then(res => {
						if(config.debeg) console.log('读取详情', res)
						this.formData = res.item;
						
						this.isAdmin = role == 'tiaojie_admin';
						this.isEmployee = role == 'tiaojie_employee';
						
						// article_status -1不予受理，2待受理，3已受理，11已完结
						const status = this.formData.article_status;
						
						// 管理员或调解员，审核与查看
						if(this.isAdmin || this.isEmployee){
							if(status == 2){
								this.action = 'audit';
								uni.setNavigationBarTitle({
									title: '受理'
								})
							}else if(status == 3){
								this.action = 'working';
								uni.setNavigationBarTitle({
									title: '详情'
								})
							} else{
								this.action = 'view';
								uni.setNavigationBarTitle({
									title: '详情'
								})
							}
						}
						// 用户，修改或查看
						else{
							if(status == 2){
								this.action = "editApply";
								uni.setNavigationBarTitle({
									title: '修改'
								})
							}else{
								this.action = "view";
								uni.setNavigationBarTitle({
									title: '详情'
								})
							}
						}
					})
			},
			submit() {
				this.disabled = true;
				this.loading = true;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.submitForm();
					} else {
						this.disabled = false;
						this.loading = false;
					}
				})
			},
			// 提交申报
			submitForm() {
				this.formData.article_status = 2;
				
				this.formData._add_user = vk.getVuex("$user.userInfo._id");
				this.formData._add_user_name = vk.getVuex("$user.userInfo.nickname");
				this.formData._add_time = new Date().getTime();
				this.formData._add_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
								
				// 如果是申请人本人填写，则同步个人信息
				if (!vk.getVuex("$user.userInfo.role[0]")) {
					this.formData.applicant_id = vk.getVuex("$user.userInfo._id");
					this.saveProfile();
					this.formData.source = '当事人申请';
				}
				
				// 提交
				let url = this.id ? this.$api.EditNews : this.$api.AddNews;
				console.log('提交', url, this.formData);
				
				vk.callFunction({
						url,
						loading: true,
						data: this.formData
					})
					.then(res => {
						console.log('提交成功 res', res);
						this.sendNotice(res.id);
						// vk.alert('申报成功，请在“调解进程”中关注受理状态。', '申报成功', '确定', () => {
						// 	// vk.navigateToHome();
						// 	this.sendNotice(res.id);
						// });
					})
			},
			// 发送 新申请通知 给调委会
			sendNotice(case_id){
				vk.callFunction({
						url: this.$api.SendNewApply,
						data:{
							case_id,
							user_name: this.formData.applicant_name
						},
						needAlert: false,
						success: res => {
							// console.log('新申请通知 res', res);
						},
						fail: err => {
							// console.log('新申请通知 err', err);
						},
						complete: () => {
							vk.alert('申报成功，请在“调解进程”中关注受理状态。', '申报成功', '确定', () => {
								vk.navigateToHome();
							});
						}
					})
			},
			saveProfile() {
				let data = {
					_id: vk.getVuex("$user.userInfo._id"),
					nickname: this.formData.applicant_name,
					id_number: this.formData.applicant_id_number,
					sex: this.formData.applicant_sex,
					age: this.formData.applicant_age,
					mobile: this.formData.applicant_phone,
					address: this.formData.applicant_address,
				}
				vk.callFunction({
					url: this.$api.RegisterProfile,
					data,
					success: (res) => {
						vk.setVuex("$user.userInfo", res.info);
					}
				})
			},
			// 撤回
			withdraw(){
				vk.confirm("撤回将删除本次申报，无法再次修改及提交本次申报，确定撤回申报吗？", "撤回申报", "确定", "取消", (res) => {
					if (res.confirm) {
						this.disabled = true;
						this.loading = true;
						vk.callFunction({
								url: this.$api.WithdrawNews,
								loading: true,
								data: {
									_id: this.formData._id
								}
							})
							.then(res => {
								vk.alert('申报已撤回', '撤回成功', '确定', () => {
									vk.navigateToHome();
								});
							})
					}
				});
			},
			audit(status) {
				this.disabled = true;
				this.loading = true;
				
				// 提交
				let url = this.$api.EditNews;
				console.log('审核', url, this.formData);
					
				if (status == -1){
					vk.prompt("请输入不予受理的原因", "提示", "确定", "取消", (res) => {
						if (res.confirm) {
							this.formData.article_status = status;
							this.formData.audit_reject_reason = res.content;
							
							this.formData._audit_user = vk.getVuex("$user.userInfo._id");
							this.formData._audit_user_name = vk.getVuex("$user.userInfo.nickname");
							this.formData._audit_time = new Date().getTime();
							this.formData._audit_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
							
							vk.callFunction({
									url,
									loading: true,
									data: this.formData
								})
								.then(res => {
									console.log('拒绝成功 res', res);
									this.sendRefuse(res.id);
								})
						}
					}, "");
				} 
				else if (status == 3) {
					this.formData.article_status = status;
					this.formData._audit_user = vk.getVuex("$user.userInfo._id");
					this.formData._audit_user_name = vk.getVuex("$user.userInfo.nickname");
					this.formData._audit_time = new Date().getTime();
					this.formData._audit_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
					
					// 生成卷宗编号 article_number
					vk.callFunction({
						url: this.$api.genCaseArticleNumber
					}).then(res => {
						this.formData.article_number = res.article_number;
						this.formData._apply_user = this.formData._add_user;
						this.formData._apply_user_name = this.formData._add_user_name;
						this.formData._apply_time = new Date().getTime();
						this.formData._apply_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
						this.formData._register_user = vk.getVuex("$user.userInfo._id");
						this.formData._register_user_name = vk.getVuex("$user.userInfo.nickname");
						this.formData._register_time = new Date().getTime();
						this.formData._register_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
						
						vk.callFunction({
								url,
								loading: true,
								data: this.formData
							})
							.then(res => {
								console.log('受理成功 res', res);
								this.sendAccept(res.id);
								
							})
					})
					
				}
				this.disabled = false;
				this.loading = false;
			},
			// 发送 受理通知 给申请人
			sendAccept(case_id){
				vk.callFunction({
						url: this.$api.SendAccept,
						data: {
							case_id,
							article_number: this.formData.article_number,
							user_ids: [this.formData.applicant_id],
							user_phones: [this.formData.applicant_phone],
						},
						needAlert: false,
						success: res => {
							// console.log('受理通知 res', res);
						},
						fail: err => {
							// console.log('受理通知 err', err);
						},
						complete: () => {
							vk.alert('受理成功', '受理成功', '确定', () => {
								vk.reLaunch('./list?action=audit&title=最新申请');
							});
						}
					})
			},
			// 发送 驳回通知 给申请人
			sendRefuse(case_id){
				vk.callFunction({
						url: this.$api.SendRefuse,
						data: {
							case_id,
							user_ids: [this.formData.applicant_id],
							user_phones: [this.formData.applicant_phone],
							audit_reject_reason: this.formData.audit_reject_reason,
						},
						needAlert: false,
						success: res => {
							// console.log('驳回通知 res', res);
						},
						fail: err => {
							// console.log('驳回通知 err', err);
						},
						complete: () => {
							vk.toast("不予受理", "none", 1000, true, () => {
								vk.reLaunch('./list?action=audit&title=最新申请');
							});
						}
					})
			},
			// 完成
			over(){
				this.disabled = true;
				this.loading = true;
				
				this.formData.article_status = 11; 
				this.formData._over_user = vk.getVuex("$user.userInfo._id");
				this.formData._over_user_name = vk.getVuex("$user.userInfo.nickname");
				this.formData._over_time = new Date().getTime();
				this.formData._over_time_str = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
				
				// 提交
				let url = this.$api.EditNews;
				
				vk.callFunction({
						url,
						loading: true,
						data: this.formData
					})
					.then(res => {
						console.log('提交成功 res', res);
						vk.reLaunch('./list?action=working&title=正在办理');
					})
			}
		}
	}
</script>
